
const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends cc.Component {

    @property(cc.Node)
    moveNode:cc.Node=null;

    @property()
    speed:number=0;
    
    joyStickBtn:cc.Node;
    dir:cc.Vec2;


    onLoad () {
        cc.debug.setDisplayStats(false);
        this.joyStickBtn=this.node.children[0];

        let coll=cc.director.getCollisionManager();
        coll.enabled=true;
        //coll.enabledDebugDraw=true;

        this.dir = cc.v2(0, 0);

        // touch event
        this.node.on('touchstart', this.onTouchStart, this);
        this.node.on('touchmove', this.onTouchMove, this);
        this.node.on('touchend', this.onTouchEnd, this);
        //外部监听事件
        this.node.on('touchcancel', this.onTouchCance, this);
    }

 
    start () {

    }

    update (dt) {
     
        //控制滚轮的半径不能越界
        let len = this.joyStickBtn.position.mag();      //长度
        let radius =this.node.width/2;                  //半径
        let ratio = len / radius;                       //比值
        // 半径不能越界
        if (ratio > 1) {
            this.joyStickBtn.position=this.joyStickBtn.position.div(ratio);
        }

        //移动
        if(this.moveNode){
            let dis=this.dir.mul(this.speed*ratio*dt);
            let newPos= cc.v2(this.moveNode.position).add(dis);
            //阻止越界
            // if(this.node.getBoundingBox().contains(newPos)){
            //     this.moveNode.position=cc.v3(newPos);
            // }
            this.moveNode.position=cc.v3(newPos);           
        }
    }

    onTouchStart(event:cc.Event.EventTouch){
        let pos =this.node.convertToNodeSpaceAR(event.getLocation());
        this.joyStickBtn.position=cc.v3(pos);
        
    }

    onTouchMove(event:cc.Event.EventTouch){
        let posDelta = event.getDelta();
        this.joyStickBtn.setPosition(this.joyStickBtn.position.add(cc.v3(posDelta)));
                
        // get direction
        this.dir = cc.v2(this.joyStickBtn.position.normalize());
    }

    onTouchEnd(event:cc.Event.EventTouch){
        this.joyStickBtn.position=cc.v3();
    }

    onTouchCance(event:cc.Event.EventTouch){
        this.joyStickBtn.position=cc.v3();
    }
}
